#pragma once
extern "C"
{
#include "libavutil/opt.h"
#include "libavutil/channel_layout.h"
#include "libavutil/common.h"
#include "libavutil/imgutils.h"
#include "libavutil/mathematics.h"
#include "libavutil/samplefmt.h"
#include "libavutil/time.h"
#include "libavutil/fifo.h"
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavformat/avio.h"
#include "libavfilter/avfilter.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
}

#include <string>
#include <openssl/sha.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <memory>
#include <list>
using namespace std;

class FileParser
{

public:
    FileParser()
    {
        return;
    }
    ~FileParser()
    {
        av_release();
    }

    int get_extra_data(string filename);

    AVFormatContext *input_context = NULL;
    int audio_index = -1;
    int video_index = -1;
    std::string sps;
    std::string pps;
    std::string vps;
    float frame_rate;
    int sample_rate;
    int get_avpacket(string inputfile, list<AVPacket *>* packet_vecs, int data_type, int flag = 0);
    AVCodecContext *decode_context = NULL; // audio decoder
    AVCodecContext *encode_context = NULL; // audio encoder

    unsigned char *first_video_extra = NULL; // include sei sps pps vps
    int first_video_extra_len = 0;

    unsigned char *first_audio_extra = NULL; // aac header
    int first_audio_extra_len = 0;

    int av_release();
    int do_av_seek(float start_time);
    bool is_h264 = false;
    bool is_no_seek = false;

private:
    int open_input(string inputfile);
    int get_audio_coder();
    int filter_frame(AVFrame *frame, int flag, list<AVPacket *>* frame_vecs);

    AVBSFContext *aac_bsf_ctx = NULL;
    AVBitStreamFilter *aac_bsf_filter = NULL; // aac bit stream filter

    AVFilterContext *bf_src_ctx_audio = NULL;         // audio filter
    AVFilterContext *bf_sink_ctx_audio = NULL;        // audio filter
    AVFilterGraph *audio_graph = NULL;                // audio filter
    const AVBitStreamFilter *video_abs_filter = NULL; // AnnexB bitstream
    AVBSFContext *video_abs_ctx = NULL;               // AnnexB bitstream
    int audio_base = -1;
    int video_base = -1;
    unsigned char *extra_data;
    int extra_data_len;
    int64_t pts = 0; // 裸h264 h265文件没有pts 需要自己生成
    int64_t last_pts = 0;
};